package com.gqj.meter.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.gqj.common.annotation.Log;
import com.gqj.common.constant.UserConstants;
import com.gqj.common.core.controller.BaseController;
import com.gqj.common.core.domain.AjaxResult;
import com.gqj.common.core.page.TableDataInfo;
import com.gqj.common.enums.BusinessType;
import com.gqj.common.utils.StorageUtil;
import com.gqj.common.utils.poi.ExcelUtil;
import com.gqj.meter.domain.*;
import com.gqj.meter.domain.vo.MdStockPosInfoVo;
import com.gqj.meter.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.util.List;
import java.util.Map;


/**
 * 储位信息Controller
 *
 * @author lxq
 * @date lxq-01-09
 */
@Api(value = "/meter/mdStockPosInfo", description = "储位信息")
@RestController
@RequestMapping("/meter/mdStockPosInfo")
public class MdStockPosInfoController extends BaseController {
    @Autowired
    private IMdStockPosInfoService mdStockPosInfoService;
    @Value("${downloadPath}")
    private String downloadPath;
    @Autowired
    private IMdMeterService mdMeterService;
    @Autowired
    private IMdLcEquipService mdLcEquipService;
    @Autowired
    private IMdItService mdItService;
    @Autowired
    private IMdComModuleService mdComModuleService;
    @Autowired
    private IMdConcentratorService mdConcentratorService;
    @Autowired
    private IMdInTaskDetailsService mdInTaskDetailsService;
    @Autowired
    private IMdOutTaskDetailsService mdOutTaskDetailsService;
    @Autowired
    private IMdOtherMaterialService mdOtherMaterialService;

    /**
     * 查询储位信息列表
     */
    @ApiOperation("查询储位信息列表")
    @PreAuthorize("@ss.hasPermi('storage:mdStockPosInfo:list')")
    @GetMapping("/list")
    public TableDataInfo list(MdStockPosInfo mdStockPosInfo) {
        startPage();
        List<MdStockPosInfo> list = mdStockPosInfoService.selectMdStockPosInfoList(mdStockPosInfo);
        return getDataTable(list);
    }

    /**
     * 导出储位信息列表
     */
    @ApiOperation("导出储位信息列表")
    @PreAuthorize("@ss.hasPermi('storage:mdStockPosInfo:export')")
    @Log(title = "储位信息", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, MdStockPosInfo mdStockPosInfo) {
        List<MdStockPosInfo> list = mdStockPosInfoService.selectMdStockPosInfoList(mdStockPosInfo);
        ExcelUtil<MdStockPosInfo> util = new ExcelUtil<MdStockPosInfo>(MdStockPosInfo.class);
        util.exportExcel(response, list, "储位信息数据");
    }

    /**
     * 获取储位信息详细信息
     */
    @ApiOperation("获取储位信息详细信息")
    @PreAuthorize("@ss.hasPermi('storage:mdStockPosInfo:query')")
    @GetMapping(value = "/{storeLocId}")
    public AjaxResult getInfo(@PathVariable("storeLocId") Long storeLocId) {
        return success(mdStockPosInfoService.selectMdStockPosInfoByStoreLocId(storeLocId));
    }

    /**
     * 新增储位信息
     */
    @ApiOperation("新增储位信息")
    @PreAuthorize("@ss.hasPermi('storage:mdStockPosInfo:add')")
    @Log(title = "储位信息", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody MdStockPosInfo mdStockPosInfo) {
        if (null == mdStockPosInfo.getStoreLocId() || 0 == mdStockPosInfo.getStoreLocId()) {
            return AjaxResult.error("新增失败，储位ID为空！");
        }
        MdStockPosInfo tempEntity = mdStockPosInfoService.selectMdStockPosInfoByStoreLocId(mdStockPosInfo.getStoreLocId());
        if (null != tempEntity) {
            return AjaxResult.error("新增'" + mdStockPosInfo.getStoreLocName() + "'失败，储位ID已存在！");
        }
        if (UserConstants.NOT_UNIQUE.equals(mdStockPosInfoService.checkStoreLocNoUnique(mdStockPosInfo))) {
            return AjaxResult.error("新增'" + mdStockPosInfo.getStoreLocName() + "'失败，储位编号已存在！");
        }
        return toAjax(mdStockPosInfoService.insertMdStockPosInfo(mdStockPosInfo));
    }

    /**
     * 修改储位信息
     */
    @ApiOperation("修改储位信息")
    @PreAuthorize("@ss.hasPermi('storage:mdStockPosInfo:edit')")
    @Log(title = "储位信息", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody MdStockPosInfo mdStockPosInfo) {
        if (null == mdStockPosInfo.getStoreLocId() || 0 == mdStockPosInfo.getStoreLocId()) {
            return AjaxResult.error("修改失败，储位ID为空！");
        }
        if (UserConstants.NOT_UNIQUE.equals(mdStockPosInfoService.checkStoreLocNoUnique(mdStockPosInfo))) {
            return AjaxResult.error("修改'" + mdStockPosInfo.getStoreLocName() + "'失败，储位编号已存在！");
        }
        return toAjax(mdStockPosInfoService.updateMdStockPosInfo(mdStockPosInfo));
    }

    /**
     * 删除储位信息
     */
    @ApiOperation("删除储位信息")
    @PreAuthorize("@ss.hasPermi('storage:mdStockPosInfo:remove')")
    @Log(title = "储位信息", businessType = BusinessType.DELETE)
    @DeleteMapping("/{storeLocIds}")
    public AjaxResult remove(@PathVariable Long[] storeLocIds) {

        for (Long storeLocId : storeLocIds) {
            //查询储位是否被引用
            int i = 0;
            //电能表
            List<MdMeter> meterList = mdMeterService.selectMdMeterList(new MdMeter() {{
                setStoreLocId(storeLocId);
            }});
            List<MdLcEquip> mdLcEquipList = mdLcEquipService.selectMdLcEquipList(new MdLcEquip() {{
                setStoreLocId(storeLocId);
            }});
            List<MdIt> mdItList = mdItService.selectMdItList(new MdIt() {{
                setStoreLocId(storeLocId);
            }});
            List<MdComModule> comModuleList = mdComModuleService.selectMdComModuleList(new MdComModule() {{
                setStoreLocId(storeLocId);
            }});
            List<MdConcentrator> concentratorList = mdConcentratorService.selectMdConcentratorList(new MdConcentrator() {{
                setStoreLocId(storeLocId);
            }});
            List<MdOtherMaterial> otherMaterialList = mdOtherMaterialService.selectMdOtherMaterialList(new MdOtherMaterial() {{
                setStoreLocId(storeLocId);
            }});
            List<MdInTaskDetails> mdInTaskDetailsList = mdInTaskDetailsService.selectMdInTaskDetailsList(new MdInTaskDetails() {{
                setStoreLocId(storeLocId);
            }});
            List<MdOutTaskDetails> mdOutTaskDetailsList = mdOutTaskDetailsService.selectMdOutTaskDetailsList(new MdOutTaskDetails() {{
                setStoreLocId(storeLocId);
            }});
            if (meterList.size() > 0 || mdLcEquipList.size() > 0 || mdItList.size() > 0 || comModuleList.size() < 0 || concentratorList.size() > 0 || otherMaterialList.size() > 0 || mdInTaskDetailsList.size() > 0 || mdOutTaskDetailsList.size() > 0) {
                i++;
            }

            if (i > 0) {
                return AjaxResult.error("储位标识" + storeLocId + "已被引用，无法删除！");
            }


        }
        return toAjax(mdStockPosInfoService.deleteMdStockPosInfoByStoreLocIds(storeLocIds));
    }

    /**
     * 查询储位下拉框
     */
    @ApiOperation("查询储位下拉框")
    @PreAuthorize("@ss.hasPermi('storage:mdStockPosInfo:mdStockPosInfoOptions')")
    @GetMapping("/mdStockPosInfoOptions")
    public AjaxResult mdStockPosInfoOptions(MdStockPosInfo mdStockPosInfo) {
        List<Map<String, Object>> list = mdStockPosInfoService.mdStockPosInfoOptions(mdStockPosInfo);
        return AjaxResult.success(list);
    }

    /**
     * 下载储位json文件
     */
    @ApiOperation("下载储位json文件")
    @PreAuthorize("@ss.hasPermi('storage:mdStockPosInfo:downloadJsonMdStockPosInfo')")
    @GetMapping("/downloadJsonMdStockPosInfo")
    public AjaxResult downloadJsonMdStockPosInfo(MdStockPosInfo mdStockPosInfo) {
        List<MdStockPosInfo> pos = mdStockPosInfoService.selectMdStockPosInfoList(mdStockPosInfo);
        List<MdStockPosInfoVo> vos = StorageUtil.copyList(pos, MdStockPosInfoVo::new);

        String orderNo = StorageUtil.getOrderNoTo12();
        String fileName = downloadPath;
        String jsonStringAc = JSON.toJSONString(vos);
        StorageUtil.createJsonFile(jsonStringAc, fileName, "储位数据"+orderNo);
        return AjaxResult.success(fileName+"储位数据"+orderNo);
    }

    /**
     * 获取储位统计信息
     */
    @ApiOperation("获取储位统计信息")
    @PreAuthorize("@ss.hasPermi('storage:mdStockPosInfo:mdStockStatistics')")
    @GetMapping("/getStockStatistics")
    public AjaxResult getStockStatistics() {
        List<Map<String, String>> map = mdStockPosInfoService.getStockStatistics();
        return success(map);
    }

    /**
     * 获取货位利用率统计数据
     */
    @ApiOperation("获取货位利用率统计数据")
    @PreAuthorize("@ss.hasPermi('storage:mdStockPosInfo:mdStockPosAvailability')")
    @GetMapping("/getPosAvailability")
    public AjaxResult getPosAvailability() {
        List<MdStockPosInfo> mdStockPosInfoList = mdStockPosInfoService.getPosAvailability();
        List<DataMap> vos = StorageUtil.copyList(mdStockPosInfoList, DataMap::new);
        return success(vos);
    }

    public static class DataMap {
        private String storeLocName;
        private Integer storeEquipNum;
        private Integer actualCount;
        private String whName;
        private String whAreaname;
        private String storeAreaName;
        private String occupancy;

        public String getOccupancy() {
            return occupancy;
        }

        public void setOccupancy(String occupancy) {
            this.occupancy = occupancy;
        }

        public String getWhName() {
            return whName;
        }

        public void setWhName(String whName) {
            this.whName = whName;
        }

        public String getWhAreaname() {
            return whAreaname;
        }

        public void setWhAreaname(String whAreaname) {
            this.whAreaname = whAreaname;
        }

        public String getStoreAreaName() {
            return storeAreaName;
        }

        public void setStoreAreaName(String storeAreaName) {
            this.storeAreaName = storeAreaName;
        }

        public String getStoreLocName() {
            return storeLocName;
        }

        public void setStoreLocName(String storeLocName) {
            this.storeLocName = storeLocName;
        }

        public Integer getStoreEquipNum() {
            return storeEquipNum;
        }

        public void setStoreEquipNum(Integer storeEquipNum) {
            this.storeEquipNum = storeEquipNum;
        }

        public Integer getActualCount() {
            return actualCount;
        }

        public void setActualCount(Integer actualCount) {
            this.actualCount = actualCount;
        }
    }

    @ApiOperation("下载储位模板")
    @PostMapping("/importTemplateMdStockPosInfo")
    @PreAuthorize("@ss.hasPermi('storage:mdStockPosInfo:importTemplateMdStockPosInfo')")
    public void importTemplateMdStockPosInfo(HttpServletResponse response) {
        ExcelUtil<MdStockPosInfo> util = new ExcelUtil<MdStockPosInfo>(MdStockPosInfo.class);
        util.importTemplateExcel(response, "储位数据");
    }

    /**
     * 导入储位execl文件
     */
    @ApiOperation("导入储位execl文件")
    @Log(title = "导入储位xecl文件", businessType = BusinessType.IMPORT)
    @PreAuthorize("@ss.hasPermi('storage:mdStockPosInfo:importDataMdStockPosInfo')")
    @PostMapping("/importDataMdStockPosInfo")
    public AjaxResult importDataMdStockPosInfo(MultipartFile file, boolean updateSupport) throws Exception {
        ExcelUtil<MdStockPosInfo> util = new ExcelUtil<MdStockPosInfo>(MdStockPosInfo.class);
        List<MdStockPosInfo> mdStockPosInfoList = util.importExcel(file.getInputStream());
        String operName = getUsername();
        String message = mdStockPosInfoService.importMdStorageAreaInfo(mdStockPosInfoList, updateSupport, operName);
        return success(message);
    }

    /**
     * 接收json文件并处理
     */
    @ApiOperation("接收json文件并处理")
    @Log(title = "接收json文件并处理", businessType = BusinessType.IMPORT)
    @PreAuthorize("@ss.hasPermi('storage:mdStockPosInfo:receiveMdStockPosInfoJsonData')")
    @PostMapping("/receiveMdStockPosInfoJsonData")
    public AjaxResult receiveMdStockPosInfoJsonData(@RequestParam("file") MultipartFile file) throws Exception {
        InputStream inputStream = file.getInputStream();
        String JsonContext = StorageUtil.ReadFile(inputStream);
        List<MdStockPosInfo> mdStockPosInfoList = JSONArray.parseArray(JsonContext, MdStockPosInfo.class);//JSON数据转化为数组　　

        for (MdStockPosInfo d : mdStockPosInfoList) {
            System.out.println(d.getStoreLocName());
        }

        return success();
    }

}
